package com.imooc.distributedemo.resume.leetcode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * leetcode169 多数元素
 */
public class Solution169 {
    public static void main(String[] args) {
//        int[] nums = {2,2,1,1,1,2,2};
        int[] nums = {2,3,3};
        int data = majorityElement(nums);
        System.out.println(data);
    }

    public static int majorityElement(int[] nums) {
        if(null==nums||nums.length<1){
            return -1;
        }
        List<Integer> set = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            set.add(nums[i]);
        }
        Map<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < set.size(); i++) {
            map.put(set.get(i),map.getOrDefault(set.get(i),0)+1);
        }
        int max = 0;
        for (Map.Entry<Integer,Integer> entry:map.entrySet()){
            Integer key = entry.getKey();
            Integer value = entry.getValue();
            if(value.doubleValue()/set.size()>(double)1/2){
                return key;
            }
        }
        return -1;
    }
}
